package ua.com.softway.db.batch;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

/** 
 * Make batching by iterating over between min and max id
 * 
 *  IDs should be ints
 */
public class IdRangeBatcher implements Batcher {

    private final int batchSize;
    
    public IdRangeBatcher(int batchSize, Criteria criteria) {
        this.batchSize = batchSize;
        
        currentId = ((Number) criteria.setProjection(Projections.min("id")).uniqueResult()).intValue();
        maxId = ((Number) criteria.setProjection(Projections.max("id")).uniqueResult()).intValue();
    }
    
    private int currentId;
    private int maxId;
    
    @SuppressWarnings("unchecked")
    @Override
    public List<Object> nextBatch(Criteria criteria) {
        if (currentId > maxId) return null;
        
        List<Object> r = criteria
            .add(Restrictions.between("id", currentId, currentId + batchSize - 1))
            .list();
        
        currentId = currentId + batchSize;
        
        return r;
    }

}
